// pages/add_Bankcards/add_Bankcards.js
import api from '../../Sendingmethod/Sendingmethod'
import
encrypt
from "../../utils/crypto-util.js"
import util from '../../utils/util'
Page({

    /**
     * 页面的初始数据
     */
    data: {
        textarr: [{
                text: "银行卡号",
                value: ""
            },
            {
                text: "开户行",
                value: ""
            },
            {
                text: "持卡人",
                value: ""
            },
            {
                text: "预留手机",
                value: ""
            },
            {
                text: "请输入验证码",
                value: ""
            },
        ],
        maskblen: false,
        fromdata: {
            number: '',
            account_bank: '',
            card_holder: "",
            mobile: '',
        },
        zhuyao:{
            bank_code: "",
            bank_id: '',
            bank_name: ''
        },
        cardnumber: ""

    },


    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {

    },
    /**
     * 
     * 非空验证
     */
    feikongyanz() {
        function countEmptyValues(obj) {
            return Object.keys(obj).reduce((count, key) => {
                // 判断是否为空值（根据需求调整条件）
                if (obj[key] === "" || obj[key] === null || obj[key] === undefined) {
                    return count + 1;
                }
                return count;
            }, 0);
        }
        let num = countEmptyValues(this.data.fromdata)
        console.log(num,this.data.fromdata, '空的个数');


        if (num > 0) {
            this.setData({
                maskblen: false
            })
        } else {
            this.setData({
                maskblen: true
            })
        }
    },
    /**
     * 输入事件
     */
    inputfun(e) {
        console.log(e);
        let zhi = e.currentTarget.dataset.index
        let data = `fromdata.${zhi}`
        this.setData({
            [data]: e.detail.value
        })
        this.feikongyanz()

    },
    /**
     * 添加银行卡
     */
    addcards() {
        console.log('添加银行卡');
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    /**
     *扫码银行卡
     */
    async saomaka() {
        // let res =await api.userbankcard({

        // })
    },

    /**
     * 图片选择
     */
    updateimg(e) {
        let _that = this
        console.log(e.target.dataset.type);
        wx.chooseMedia({
            count: 1, // 可选择的图片数量
            mediaType: ['image'],
            sizeType: ['compressed'], // 压缩图片
            sourceType: ['album', 'camera'], // 来源：相册或相机
            success: (res) => {
                console.log(res);
                this.imgeuplode(res.tempFiles[0], 'front')
                // 将选择的图片上传到服务器

                // this.panduan()

            }
        })
    },
    getUuid() {
        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
            var r = (Math.random() * 16) | 0,
                v = c == 'x' ? r : (r & 0x3) | 0x8;
            return v.toString(16);
        });
    },

    /**
     * 银行卡上传
     * 
     */
    imgeuplode(data) {
        wx.showLoading({
            mask: true
        })
        // 获取当前时间戳
        let datatime = new Date().getTime()
        console.log(data);
        let Randomnum = this.getUuid()
        let aecdata
        let md5
        let _that = this
        let fromarr2 = `fromarr[${2}].value`;
        let fromarr1 = `fromarr[${1}].value`;
        md5 = encrypt.md5(`sign:data=&nonceStr=${Randomnum}&timestamp=${datatime}`)
        wx.uploadFile({
            url: 'https://api.business.dayenginer.com/user/bankcard',
            filePath: data.tempFilePath,
            formData: {},
            name: 'file',
            header: {
                "h_uid": wx.getStorageSync('userid') ? wx.getStorageSync('userid') : '',
                "h_timestamp": datatime,
                "h_nonceStr": Randomnum,
                "h_sign": md5,
                "h_token": wx.getStorageSync('token') ? wx.getStorageSync('token') : '',
                "h_deviceId": '',
                'Content-Type': 'multipart/form-data'
            },
            success(res) {
                console.log(res, "上传成功");
                let data = JSON.parse(encrypt.aesDecrypt(res.data))
                console.log(data, '银行卡卡号');
                //判断
                if (data.data.number) {
                    _that.setData({
                        ['fromdata.number']:data.data.number
                    })
                    _that.numbercard(data.data.number)
                }
                // _that.panduan()
            },
            fail(res) {
                console.log(res, '上传失败');
                console.log(JSON.parse(encrypt.aesDecrypt(res.data)));
                wx.hideLoading()
            }
        })
    },

    /**
     * 
     * 银行卡号截取
     */
    cardnum(num) {
        const chunkSize = 4;
        let result = [];
        for (let i = 0; i < num.length; i += chunkSize) {
            // 截取当前四位
            const chunk = num.slice(i, i + chunkSize);
            result.push(chunk);
        }
        return result.join("-");
    },
    /**
     * 获取银行卡信息
     */
    async numbercard(num) {
        let res = await api.userbankbynum({
            number: num
        })

        console.log(res, '银行卡信息');
        this.cardnum(num)
        console.log(    this.cardnum(num),'切割卡号');
        if (res.code == 0) {
            wx.hideLoading()
            this.setData({
                fromdata: {
                    ...this.data.fromdata,
                    ...res.data,
                    qigenumber: this.cardnum(num)
                }
            })
        } else {
            wx.hideLoading()
        }
        this.feikongyanz()
    },

    /**
     * 添加银行卡
     */
    async getuserbankcardadd() {
        wx.showLoading({
            mask: true
        })
        let res = await api.userbankcardadd({
            ...this.data.fromdata
        })
        console.log(res, '添加银行卡');
        if (res.code == 0) {
            setTimeout(() => {
                wx.hideLoading()
            }, 500)
            wx.showToast({
                title: res.msg,
                icon: "success",
                duration: 2000
            })
            setTimeout(() => {
                wx.navigateBack(1)
            }, 500)
        } else {
            setTimeout(() => {
                wx.hideLoading()
            }, 500)
            wx.showToast({
                title: res.msg,
                icon: "error",
                duration: 2000
            })

        }
    },
    tijiaofagdu: util.throttle(function () {
        this.getuserbankcardadd()
    }, 1000),
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})